<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-card>
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="用户ID">
              <el-input v-model="formInline.id"></el-input>
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="formInline.name"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="formInline.email"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="formInline.phone"></el-input>
            </el-form-item>
            <el-form-item label="用户角色" prop="role">
            <el-select v-model="formInline.role" placeholder="请选择用户角色">
                <el-option label="全部" value=""></el-option>
                <el-option label="普通用户" value="普通用户"></el-option>
                <el-option label="会员" value="会员"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-config-provider :locale="locale">
                <el-date-picker
                  v-model="formInline.create_time"
                  type="date"
                  placeholder="选择日期时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :locale="locale"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item label="修改时间">
              <el-config-provider :locale="locale">
                <el-date-picker
                  v-model="formInline.update_time"
                  type="date"
                  placeholder="选择日期时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :locale="locale"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button type="info" @click="resetQueryData">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-loading="isLoading" element-loading-text="加载中...">
          <el-form-item style="float: right;">
              <el-button type="success" @click="showAddDialog = true">新增</el-button>
              <el-button type="warning" @click="handleBatchDelete" >批量删除</el-button>
              <el-button type="danger" @click="deleteAll" >清空数据</el-button>
            </el-form-item>
          <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="70" align="center" style = "background-color :black">
              <template #default="scope">
                <div class="serial-number">
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="用户ID" width="100"></el-table-column>
            <el-table-column prop="name" label="用户名" width="100"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="phone" label="联系电话"></el-table-column>
            <el-table-column prop="role" label="用户角色"></el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column prop="updateTime" label="修改时间"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
                <el-button size="small" type="danger" @click="handleDelete([scope.row.id])">删除</el-button>
                <el-button size="small" type="primary" @click="handleReset(scope.row)">重置密码</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px; margin-bottom: 20px; text-align: right; float: right;">
            <el-config-provider :locale="locale">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              ></el-pagination>
            </el-config-provider>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 引入新增停车场对话框组件 -->
    <AddUserDialog 
      :visible="showAddDialog" 
      @update:visible="showAddDialog = $event"
      @add="handleAdd"
    />
    <EditUserDialog 
      :visible="showEditDialog" 
      :userId="updateUserId"
      :updateName="updateName"
      :updateEmail="updateEmail"
      :updatePhone="updatePhone"
      :updateRole="updateRole"
      @update:visible="showEditDialog = $event"
      @edit="fetchData"
    />
  </div>
</template>
<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn'; 
import { ref, watch } from 'vue';
import axios from 'axios';
import AddUserDialog from '@/components/AddUserDialog.vue';
import EditUserDialog from '@/components/EditUserDialog.vue';
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRoute } from 'vue-router';

const route = useRoute();
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const updateUserId = ref(0);
const updateName = ref('');
const updateEmail= ref('');
const updatePhone = ref('');
const updateRole= ref('');

// 初始化查询条件对象
const formInline = ref({
  id: '',
  name: '',
  email: '',
  phone: '',
  role: '',
  createTime: null,
  updateTime: null
});
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10); // 新增每页显示条数
const locale = zhCn;
const isLoading = ref(false);
const selectedIds = ref([]);

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}` // 从 localStorage 获取 token 并设置到请求头
    }
})

watch(() => route.path, (newPath) => {
  if(newPath === '/admin/UserManagement') {
    console.error("刷新UserManagement");
    fetchData(); 
  }
});
// 获取数据函数
const fetchData = async () => {
  isLoading.value = true;
  const params = {
    ...formInline.value,
    pageIndex: currentPage.value,
    pageSize: pageSize.value
  };
  Object.keys(params).forEach(key => (params[key] === '' || params[key] === null) && delete params[key]);
  if ('code' in params && params.code) {
    params.userId = params.id;
    delete params.id;
  }
  try {
    const response = await api.get('/api/v1/user/user-info', { params });
    if (response.data.code === "200") {
      if(response.data.data != null){
        let filteredData = response.data.data.records;
        filteredData = filteredData.filter(record => record.role !== '管理员');   
        tableData.value = filteredData;
        total.value = filteredData.length;
      } else {
        tableData.value = [];
      }
    } else {
      ElMessage({
        title: '错误',
        message: '获取用户记录失败！' + response.data.message,
        type: 'error',
        showClose: false
      });
    }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '获取用户记录失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    isLoading.value = false;
  }
};


const handleAdd = async () => {
  await fetchData();
};

const handleEdit = async (row) => {
  updateUserId.value = row.id;
  updateName.value = row.name;
  updateEmail.value = row.email;
  updatePhone.value = row.phone;
  updateRole.value = row.role;
  showEditDialog.value = true;
};
const handleReset = async (row) => {
  ElMessageBox.confirm(
    '此操作将重置该用户为默认密码, 是否继续?',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      type: 'warning'
    }
  ).then(async () => {
    isLoading.value = true;
    try {
      const response = await api.post('/api/v1/user/reset', row);
      console.log(JSON.stringify(row))
      if (response.data.code === "200") {
        ElMessage({
          title: '成功',
          message: '重置密码成功',
          type: 'success',
          showClose: false,
        });
      } else {
        ElMessage({
          title: '错误',
          message: '重置密码失败！' + response.data.message,
          type: 'error',
        });
      }
    } catch (error) {
      ElMessage({
        title: '错误',
        message: '重置密码失败！' + error.message,
        type: 'error',
      });
    } finally {
      isLoading.value = false;
      fetchData();
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消重置密码'
    });
  });
};
const handleDelete = async (ids) => {
  try {
    const response = await api.delete('/api/v1/user/user-info', {
       data: { ids }
    });
    if (response.data.code === "200") {
      ElMessage({
        title: '成功',
        message: '删除成功',
        type: 'success',
        showClose: false
      });
      selectedIds.value = [];
    } else {
      ElMessage({
        title: '错误',
        message: '删除失败！' + response.data.message,
        type: 'error',
        showClose: false
      });
    }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '删除失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    await fetchData();
    isLoading.value = false;
  }
};
const handleBatchDelete = async () => {
  handleDelete(selectedIds.value);
}
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchData();
};
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchData();
};
const deleteAll = async () => {
  ElMessageBox.confirm(
    '此操作将永久删除所有数据, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    isLoading.value = true;
    try {
      const response = await api.delete('/api/v1/user/all-user-info');
      if (response.data.code === "200") {
        ElMessage({
          title: '成功',
          message: '所有数据删除成功',
          type: 'success',
          showClose: false,
        });
      } else {
        ElMessage({
          title: '错误',
          message: '删除失败！' + response.data.message,
          type: 'error',
        });
      }
    } catch (error) {
      ElMessage({
        title: '错误',
        message: '删除失败！' + error.message,
        type: 'error',
      });
    } finally {
      isLoading.value = false;
      fetchData();
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
}
const resetQueryData = () =>{
  formInline.value = {
    id: '',
    name: '',
    address: '',
    latitude: '',
    longitude: '',
    operatingHours: '',
    phone: '',
    feeScheduleCode: '',
    description: '',
    createTime: null,
    updateTime: null,
    code: ''
  };
  fetchData();
}

fetchData();
</script>

<style scoped>
.admin-dashboard {
  height: 100vh;
}
.el-container {
  height: 100%;
}
.el-aside {
  background-color: #f8f9fa;
}
.el-main {
  padding: 20px;
}
.el-card {
  margin-bottom: 20px;
}
.el-table .cell {
  pointer-events: none;
}
.el-select {
  width: 180px; /* 设置你希望的宽度 */
}
</style>